package com.gosling.cloudspace.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Random;

/***
 * 文件随机设置工具类
 *
 * @author lihonglin
 * @date 2022/8/1 14:40
 */
public class ImgsSelectTool {
    protected static final Logger logger = LoggerFactory.getLogger(ImgsSelectTool.class);

    private static final String DEFAULT_HEADER_IMG = "2.png";
    private static final String DEFAULT_HEADER_IMG_SUFFIX = "../imgs/headerImgs/";

    /***
     * 随机获取/static/imgs/headerImgs目录下的一张图片作为头像
     * @return
     */
    public static String getHeaderImgFile() {
        String imgName = DEFAULT_HEADER_IMG;
        try {
            String path = ImgsSelectTool.class.getResource("/static/imgs/headerImgs").getPath();
            File file = new File(URLDecoder.decode(path ,"UTF-8"));
            if (file.exists() && file.isDirectory()) {
                File[] listFiles = file.listFiles();
                if (listFiles != null && listFiles.length > 0) {
                    //随机获取/static/imgs/headerImgs目录下的一张图片作为头像
                    Random random = new Random();
                    int randomNextInt = random.nextInt(listFiles.length);
                    imgName = listFiles[randomNextInt].getName();
                }
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return DEFAULT_HEADER_IMG_SUFFIX + imgName;
    }
}
